# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '136': {
        #  gbpays 支付宝宝到卡扫码 2.15% 1-49999 dwc
        'API_KEY': '996df8b6e7a580d4cb202f5dc12be9de',
        'gateway': 'http://api.gbpays.com/gateway.php',
        'query_gateway': 'http://api.gbpays.com/query.php',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def gen_order_sign(d, key):
    s = '{}{}{}{}{}{}{}'.format(
        d['out_trade_no'], d['price'], d['istype'], d['adduid'], d['adduser'], d['mct_id'], key
    )
    _LOGGER.info("gbpays sign string is: %s", s)
    return generate_sign(s)


def gen_verify_sign(d, key):
    s = '{}{}{}{}{}{}{}'.format(
        d['out_trade_no_'], d['price_'], d['istype_'], d['adduid_'], d['adduser_'], d['mct_id_'], key
    )
    return generate_sign(s)


def gen_query_sign(d, key):
    s = '{}{}{}'.format(
        d['out_trade_no'], d['mct_id'], key
    )
    return generate_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign_']
    params.pop('sign_')
    calculated_sign = gen_verify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("gbpays sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)
    else:
        return True


def _get_pay_type(service):
    if service == 'alipay':
        return 1
    elif service == 'wechat':
        return 2
    elif service == 'face2face':
        return 5
    elif service == 'alipay2bank':
        return 6
    return 1


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def _get_str(s, start, end):
    p1 = s.index(start)
    p2 = s.index(end, p1 + len(start))
    if p2 > p1:
        return s[p1 + len(start) + 3: p2 - 3]
    else:
        return ''


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('goodsname', 'charge'),
        ('istype', _get_pay_type(service)),
        ('adduid', 'inotech'),
        ('adduser', str(pay.user_id)),
        ('adddata', ''),
        ('price', str(pay_amount)),
        ('mct_id', app_id),
        ('out_trade_no', str(pay.id)),
        ('notify_url', '{}/pay/api/{}/gbpays/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('return_url', '{}/pay/api/{}/gbpays/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),
    ))
    parameter_dict['sign'] = gen_order_sign(parameter_dict, api_key)
    _LOGGER.info("gbpays create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['out_trade_no'])
    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    _LOGGER.info('gbpays url: %s', settings.PAY_CACHE_URL + cache_id)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("gbpays notify data: %s, order_id is: %s", data, data['out_trade_no_'])
    verify_results = verify_notify_sign(data, api_key)
    _LOGGER.info("verify_results is : %s", verify_results)
    pay_id = data['out_trade_no_']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('gbpays event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = ''
    trade_no = data['order_on_']
    total_fee = float(data['price_'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 校验成功
    if verify_results:
        _LOGGER.info('gbpays check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mct_id', app_id),
        ('out_trade_no', pay_order.id),
    ))
    parameter_dict['sign'] = gen_query_sign(parameter_dict, api_key)
    _LOGGER.info("gbpays query data: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("gbpays query rsp data: %s", response.text)
    if response.status_code == 200:
        data = response.text
        trade_status = _get_str(data, 'Order_str', 'Order_msg')
        _LOGGER.info("trade_status is: %s", trade_status)
        trade_no = _get_str(data, 'Order_on', 'out_trade_no')
        total_fee = float(_get_str(data, 'Order_price', 'Order_istype'))

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        # 支付状态。1代表已支付,-1代表未支付
        if trade_status == '1':
            _LOGGER.info('gbpays query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('gbpays data error, status_code: %s', response.status_code)
